package edu.rit.hvz.android;

import edu.rit.hvz.android.DataLayer.MissionDBAdapter;
import edu.rit.hvz.android.DataLayer.NewsDBAdapter;
import edu.rit.hvz.android.DataLayer.PlayerDBAdapter;
import edu.rit.hvz.android.DataLayer.ServerDatabaseConnection;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class NewsFeed extends ListActivity {
	private Cursor mCursor; 
	private NewsDBAdapter db = null;
	private SimpleCursorAdapter adapter;
	private EditText filterText = null;
	
	private static final int Delete_ID = Menu.FIRST;
	private static final int REQUEST_CODE = 1;
	private static final int ADD_NEWS = 2;
	private static final int REFRESH = 3;
	private static final int EDIT_NEWS = 4;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.onActivityCreateSetTheme(this);
        setContentView(R.layout.news_feed_layout);
        registerForContextMenu(getListView());	
        
        filterText = (EditText) findViewById(R.id.news_search);
        filterText.addTextChangedListener(filterTextWatcher);
        
        findViewById(R.id.createEvent).setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				addingEvent();
			}        	
        });
        
        db = new NewsDBAdapter(this);
        db.open();
        // Put a managed wrapper around the retrieved cursor so we don't have to worry about
        // requerying or closing it as the activity changes state.
        mCursor = db.getAllNews();
        startManagingCursor(mCursor);

        // Now create a new list adapter bound to the cursor.
        // SimpleListAdapter is designed for binding to a Cursor.
        adapter = new SimpleCursorAdapter(
                this, // Context.
                android.R.layout.simple_list_item_1,  // Specify the row template to use (here, two columns bound to the two retrieved cursor rows).
                mCursor,                                              // Pass in the cursor to bind to.
                new String[] {NewsDBAdapter.TITLE},           // Array of cursor columns to bind to.
                new int[] {android.R.id.text1});  // Parallel array of which template objects to bind to those columns.

        adapter.setFilterQueryProvider(new FilterQueryProvider() {

            public Cursor runQuery(CharSequence constraint) {
                String partialValue = constraint.toString();
                return db.filterNewsByName(partialValue);

            }
        });
        
        // Bind to our new adapter.
        setListAdapter(adapter);
    }	
	
	private TextWatcher filterTextWatcher = new TextWatcher() {

	    public void afterTextChanged(Editable s) {
	    }

	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }

	    public void onTextChanged(CharSequence s, int start, int before,
	            int count) {
	        adapter.getFilter().filter(s);
	        
	    }

	};
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    menu.add(0, Delete_ID, 0, "Delete");
	    menu.add(0, EDIT_NEWS, 0, "Edit");
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id){
		Intent intent = new Intent().setClass(this, Event.class);
		intent.putExtra(NewsDBAdapter.ROW_ID, id);
		this.startActivity(intent);				
	}
	
	
	public void onRestoreInstanceState(Bundle saved) {
	    super.onRestoreInstanceState(saved);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ADD_NEWS, 0, "Create new event");
        menu.add(0, REFRESH, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
        
    }
	
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        mCursor.moveToPosition(info.position);
        long id = mCursor.getLong(mCursor.getColumnIndex(db.ROW_ID));
	    switch(item.getItemId()) {
	    case Delete_ID:
	        db.open();
	        db.deleteNewsServer(id);
	        db.close();
	        ServerDatabaseConnection.populateNews(this);
	        adapter.getCursor().requery();	
	        return true;
	    case EDIT_NEWS:
	    	editEvent(id);
	    }
	    return super.onContextItemSelected(item);
	}
	
	 @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	    	case ADD_NEWS:
	    		addingEvent();
	    		return true;
	    	case R.id.settings:
				this.startActivity(new Intent(this, Preferences.class));
				return true;
	    	case REFRESH:
	    		ServerDatabaseConnection.populateNews(this);
	    		adapter.getCursor().requery();
	        }
	        return false;
	    }
	
	 public void editEvent(long id) {
			Intent intent = new Intent().setClass(this, EditEvent.class);
			intent.putExtra(NewsDBAdapter.ROW_ID, id);
			
			this.startActivityForResult(intent, REQUEST_CODE);
		}
	 
	public void addingEvent() {
		//Intent intent = new Intent().setClass(this, CreateMission.class);
		//startActivity(intent);
		//startActivityForResult(intent, REQUEST_CODE);
		
		this.startActivity(new Intent(this, EditEvent.class));
	}
	
}
